<template>
  <div class="document-management">
    <div class="left-content" :class="{ collapsed: selectedDocument }">
      <a-spin :spinning="loading" tip="加载中...">
        <div class="search-container">
          <div class="search-section">
            <a-input-search
              v-model:value="searchText"
              placeholder="搜索文件名"
              style="width: 300px"
              @search="handleSearch"
            />
            <div class="batch-actions">
              <a-button 
                type="primary" 
                danger 
                :disabled="selectedRowKeys.length === 0"
                @click="handleBatchDelete"
              >
                <template #icon><delete-outlined /></template>
                删除
              </a-button>
            </div>
          </div>
          <a-button type="primary" @click="handleAddFile">
            <template #icon><upload-outlined /></template>
            添加文件
            <input
              type="file"
              ref="fileInput"
              style="display: none"
              @change="handleFileChange"
              multiple
            />
          </a-button>
        </div>
        <a-table
          :columns="columns"
          :data-source="filteredDocuments"
          :pagination="pagination"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          :scroll="{ y: 'calc(100vh - 300px)' }"
          @row-click="handleRowClick"
          :customRow="customRow"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'name'">
              <div class="name-cell">
                <file-text-outlined style="margin-right: 8px; color: #1890ff; flex-shrink: 0;" />
                <a-input
                  v-if="editingDocument && editingDocument.key === record.key"
                  v-model:value="editingDocument.name"
                  @keyup.esc="handleEditCancel"
                  ref="editInput"
                  style="width: 100%"
                />
                <span v-else class="name-text" @click.stop="handleEditStart(record)">{{ record.name }}</span>
                <div v-if="editingDocument && editingDocument.key === record.key" class="edit-actions">
                  <a-button
                    type="text"
                    class="confirm-edit-btn"
                    @click.stop="handleEditConfirm(record)"
                  >
                    <check-outlined />
                  </a-button>
                  <a-button
                    type="text"
                    class="cancel-edit-btn"
                    @click.stop="handleEditCancel"
                  >
                    <close-outlined />
                  </a-button>
                </div>
              </div>
            </template>
            <template v-else-if="column.key === 'status'">
              <a-tag 
                :color="record.status === 'enabled' ? 'success' : 'default'"
                :style="{ cursor: 'pointer' }"
                @click.stop="handleStatusChange(record)"
              >
                {{ record.status === 'enabled' ? '启用' : '禁用' }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'embedStatus'">
              <div class="embed-status">
                <a-tooltip :title="getEmbedStatusText(record.embedStatus)">
                  <component 
                    :is="getEmbedStatusIcon(record.embedStatus)" 
                    :style="{ color: getEmbedStatusColor(record.embedStatus) }" 
                  />
                </a-tooltip>
                <span :style="{ color: getEmbedStatusColor(record.embedStatus) }">
                  {{ getEmbedStatusText(record.embedStatus) }}
                </span>
              </div>
            </template>
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button type="text" danger @click.stop="handleDelete(record)">
                  <template #icon><delete-outlined /></template>
                </a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-spin>
    </div>

    <!-- 绿色分隔容器 -->
    <div class="green-separator" :class="{ visible: selectedDocument }"></div>

    <!-- 右侧文档详情 -->
    <div class="right-content" :class="{ visible: selectedDocument }">
      <div class="detail-header">
        <div class="detail-header-content">
          <div class="header-title">
            <a-button 
              class="collapse-btn"
              type="text"
              @click="selectedDocument = null"
            >
              <right-outlined />
            </a-button>
            <a-tooltip :title="selectedDocument?.name">
              <div class="doc-title">{{ selectedDocument?.name }}</div>
            </a-tooltip>
            <span class="section-count">共 {{ sections.length }} 分段</span>
          </div>
          <div class="header-actions">
            <a-input
              v-model:value="sectionSearchText"
              placeholder="搜索内容"
              style="width: 40%; margin-left: 2px;"
              @search="handleSectionSearch"
            />
            <a-button 
              type="primary" 
              danger
              :disabled="selectedSectionKeys.length === 0"
              style="margin-right: 0px;"
              @click="handleBatchDeleteSections"
            >
              删除
            </a-button>
            <a-button 
              type="primary"
              :disabled="selectedSectionKeys.length === 0"
              style="margin-right: 0px;"
              @click="handleBatchEnableSections"
            >
              启用
            </a-button>
            <a-button 
              type="primary"
              danger
              :disabled="selectedSectionKeys.length === 0"
              style="margin-right: 0px;"
              @click="handleBatchDisableSections"
            >
              禁用
            </a-button>
            <a-button type="primary" @click="handleAddSection">
              添加分段
            </a-button>
          </div>
        </div>
      </div>
      <div class="detail-content">
        <div v-if="sections.length > 0" class="sections-container">
          <div class="sections-list">
            <div 
              v-for="section in sections" 
              :key="section.id" 
              class="section-card"
              :class="{ selected: selectedSectionKeys.includes(section.id) }"
              @click="handleSectionSelect(section.id)"
            >
              <div class="section-header">
                <div class="section-title">
                  <span class="status-dot" :class="{ enabled: section.enabled }"></span>
                  <span class="section-index">分段 {{ section.index }}</span>
                  <span class="char-count">{{ section.chars }}字</span>
                </div>
                <div class="section-actions">
                  <a-checkbox 
                    :checked="selectedSectionKeys.includes(section.id)"
                    @click.stop
                    @change="(e) => handleSectionCheckboxChange(e, section.id)"
                    class="section-checkbox"
                  />
                  <a-button type="text" @click.stop="handleEditSection(section)">
                    <template #icon><edit-outlined /></template>
                  </a-button>
                </div>
              </div>
              <div class="section-content">{{ section.content }}</div>
              <div class="section-footer">
                <div class="section-tags">
                  {{ section.tags.join(' # ') }}
                </div>
              </div>
            </div>
          </div>
          <div class="segment-pagination">
            <a-pagination
              v-model:current="segmentPagination.current"
              v-model:pageSize="segmentPagination.pageSize"
              :total="segmentPagination.total"
              :show-total="segmentPagination.showTotal"
              :page-size-options="segmentPagination.pageSizeOptions"
              @change="segmentPagination.onChange"
              @showSizeChange="segmentPagination.onShowSizeChange"
            />
          </div>
        </div>
        <div v-else class="empty-sections">
          暂无分段
        </div>
      </div>
    </div>

    <!-- 设置弹窗 -->
    <a-modal
      v-model:visible="settingsModalVisible"
      title="嵌入设置"
      @ok="handleSettingsSubmit"
      @cancel="handleSettingsCancel"
      :confirmLoading="settingsLoading"
      width="600px"
      :okText="'保存并处理'"
      :cancelText="'取消'"
    >
      <a-form
        :model="settingsForm"
        layout="vertical"
      >
        <a-divider>分段设置</a-divider>
        <a-form-item label="分段标识" required>
          <a-input
            v-model:value="displaySegmentIdentifier"
            placeholder="请输入分段标识，例如：\\n"
          />
        </a-form-item>
        <a-form-item label="分段最大长度(tokens)" required>
          <a-input-number
            v-model:value="settingsForm.maxSegmentLength"
            :min="1"
            :max="10000"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="分段重叠长度(tokens)" required>
          <a-input-number
            v-model:value="settingsForm.segmentOverlap"
            :min="0"
            :max="1000"
            style="width: 100%"
          />
        </a-form-item>

        <a-divider>文本预处理规则</a-divider>
        <a-form-item>
          <a-checkbox-group v-model:value="settingsForm.preprocessingRules">
            <a-checkbox value="remove_extra_spaces">替换掉连续的空格、换行符和制表符</a-checkbox>
            <a-checkbox value="remove_urls_emails">删除所有 URL 和电子邮件地址</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 分段编辑抽屉 -->
    <a-drawer
      v-model:open="drawerVisible"
      :title="drawerTitle"
      placement="right"
      width="500"
      @close="handleDrawerClose"
    >
      <a-form
        :model="sectionForm"
        layout="vertical"
      >
        <a-form-item label="分段内容" required>
          <a-textarea
            v-model:value="sectionForm.content"
            :rows="6"
            placeholder="请输入分段内容，支持Markdown格式"
            class="markdown-editor"
          />
        </a-form-item>
        <a-form-item label="标签">
          <div class="tags-input-container">
            <div class="tags-list">
              <a-tag
                v-for="(tag, index) in sectionForm.tags"
                :key="index"
                closable
                color="orange"
                @close="removeTag(index)"
              >
                {{ tag }}
              </a-tag>
            </div>
            <a-input
              v-model:value="tagInput"
              placeholder="输入标签，按回车添加"
              @pressEnter="addTag"
              @blur="addTag"
              class="tag-input"
            />
          </div>
        </a-form-item>
      </a-form>
      <template #footer>
        <div style="display: flex; justify-content: flex-end; gap: 8px;">
          <a-button @click="handleDrawerClose">取消</a-button>
          <a-button type="primary" @click="handleSectionSubmit">确定</a-button>
        </div>
      </template>
    </a-drawer>
  </div>
</template>

<script setup>
import { ref, computed, h, resolveComponent, nextTick, onMounted, onUnmounted, watch } from 'vue'
import {
  FileTextOutlined,
  EditOutlined,
  DeleteOutlined,
  UploadOutlined,
  CloudUploadOutlined,
  LoadingOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  WarningOutlined,
  CloudOutlined,
  PlusOutlined,
  RightOutlined,
  CheckOutlined,
  CloseOutlined,
  SettingOutlined
} from '@ant-design/icons-vue'
import { Modal } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import { useRoute } from 'vue-router'
import http from '@/utils/ai/http'

// 添加 loading 响应式变量
const loading = ref(false)

// 表格列定义
const columns = computed(() => {
  const baseColumns = [
    {
      title: '文件名',
      dataIndex: 'name',
      key: 'name',
      width: '30%',
      ellipsis: {
        showTitle: false
      },
      customCell: (record) => ({
        style: {
          maxWidth: '100%',
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis'
        }
      }),
      customRender: ({ text }) => {
        return h(resolveComponent('a-tooltip'), 
          { 
            placement: 'topLeft',
            title: text
          }, 
          {
            default: () => h('div', 
              { 
                class: 'name-cell' 
              }, 
              [
                h(FileTextOutlined, {
                  style: {
                    marginRight: '8px',
                    color: '#1890ff',
                    flexShrink: 0
                  }
                }),
                h('span', 
                  { 
                    class: 'name-text' 
                  }, 
                  text
                )
              ]
            )
          }
        )
      }
    },
    {
      title: 'token数',
      dataIndex: 'size',
      key: 'size',
      width: '10%'
    },
    {
      title: '字符数',
      dataIndex: 'chars',
      key: 'chars',
      width: '10%'
    }
  ]

  if (!selectedDocument.value) {
    baseColumns.push({
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: '15%'
    })
  }

  baseColumns.push(
    {
      title: '嵌入状态',
      key: 'embedStatus',
      width: selectedDocument.value ? '20%' : '15%'
    },
    {
      title: '状态',
      key: 'status',
      width: '10%'
    },
    {
      title: '操作',
      key: 'action',
      width: '10%',
      fixed: 'right'
    }
  )

  return baseColumns
})

// 嵌入状态常量
const EMBED_STATUS = {
  NOT_EMBEDDED: 'not_embedded',
  PROCESSING: 'processing',
  COMPLETED: 'completed',
  QUEUED: 'queued',
  FAILED: 'failed'
}

// 移除示例数据，只保留一个 documents 声明
const documents = ref([])

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: false,
  showTotal: (total) => `共 ${total} 条`,
  onChange: (page) => {
    pagination.value.current = page
  }
})

// 状态变量
const searchText = ref('')
const selectedRowKeys = ref([])
const selectedDocument = ref(null)

// 计算属性
const filteredDocuments = computed(() => {
  let result = documents.value
  if (searchText.value) {
    result = result.filter(doc => 
      doc.name.toLowerCase().includes(searchText.value.toLowerCase())
    )
  }
  pagination.value.total = result.length
  const startIndex = (pagination.value.current - 1) * pagination.value.pageSize
  return result.slice(startIndex, startIndex + pagination.value.pageSize)
})

// 嵌入状态处理函数
const getEmbedStatusIcon = (status) => {
  const iconMap = {
    [EMBED_STATUS.NOT_EMBEDDED]: CloudOutlined,
    [EMBED_STATUS.PROCESSING]: LoadingOutlined,
    [EMBED_STATUS.COMPLETED]: CheckCircleOutlined,
    [EMBED_STATUS.QUEUED]: ClockCircleOutlined,
    [EMBED_STATUS.FAILED]: WarningOutlined
  }
  return iconMap[status] || CloudOutlined
}

const getEmbedStatusText = (status) => {
  const textMap = {
    [EMBED_STATUS.NOT_EMBEDDED]: '未嵌入',
    [EMBED_STATUS.PROCESSING]: '正在嵌入',
    [EMBED_STATUS.COMPLETED]: '已完成',
    [EMBED_STATUS.QUEUED]: '排队中',
    [EMBED_STATUS.FAILED]: '嵌入失败'
  }
  return textMap[status] || '未嵌入'
}

const getEmbedStatusColor = (status) => {
  const colorMap = {
    [EMBED_STATUS.NOT_EMBEDDED]: '#8c8c8c',
    [EMBED_STATUS.PROCESSING]: '#1890ff',
    [EMBED_STATUS.COMPLETED]: '#52c41a',
    [EMBED_STATUS.QUEUED]: '#faad14',
    [EMBED_STATUS.FAILED]: '#ff4d4f'
  }
  return colorMap[status] || '#8c8c8c'
}

// 事件处理函数
const handleSearch = (value) => {
  searchText.value = value
  pagination.value.current = 1
}

const handleRowClick = (record) => {
  selectedDocument.value = record
  fetchSegments(record.key)
}

const customRow = (record) => {
  return {
    onClick: () => handleRowClick(record)
  }
}

const onSelectChange = (selectedKeys) => {
  selectedRowKeys.value = selectedKeys
}

const handleStatusChange = (record) => {
  Modal.confirm({
    title: '确认修改状态',
    content: `确定要将文档"${record.name}"的状态修改为${record.status === 'enabled' ? '禁用' : '启用'}吗？`,
    okText: '确认',
    cancelText: '取消',
    async onOk() {
      // TODO: 调用API更新状态
      const doc = documents.value.find(d => d.key === record.key)
      if (doc) {
        doc.status = doc.status === 'enabled' ? 'disabled' : 'enabled'
      }
      message.success('状态修改成功')
    }
  })
}

const editingDocument = ref(null)
const editInput = ref(null)

const handleEditStart = (record) => {
  editingDocument.value = { ...record }
  nextTick(() => {
    editInput.value?.focus()
  })
}

const handleEditConfirm = async (record) => {
  if (editingDocument.value && editingDocument.value.name.trim()) {
    try {
      // 从当前URL中获取knowledge_id
      const currentPath = window.location.pathname
      const knowledgeId = currentPath.split('/documents/')[1]
      
      if (!knowledgeId) {
        message.error('未找到知识库ID')
        return
      }

      // 获取用户信息
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      if (!userInfo.userId || !userInfo.username) {
        message.error('未找到用户信息')
        return
      }

      // 调用重命名接口
      const res = await http.post(`/knowledge_api/${knowledgeId}/doc_rename`, {
        username: userInfo.username,
        user_id: userInfo.userId,
        document_id: record.key,
        name: editingDocument.value.name
      })

      if (res.data.code === 200) {
        // 更新本地文档名称
        const doc = documents.value.find(d => d.key === record.key)
        if (doc) {
          doc.name = editingDocument.value.name
        }
        message.success('文件名修改成功')
      } else {
        message.error(res.data.message || '文件名修改失败')
      }
    } catch (error) {
      console.error('修改文件名失败:', error)
      message.error(error.response?.data?.message || '文件名修改失败')
    }
  }
  editingDocument.value = null
}

const handleEditCancel = () => {
  editingDocument.value = null
}

const handleEdit = (record) => {
  handleEditStart(record)
}

const handleDelete = (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除文档"${record.name}"吗？`,
    okText: '确认',
    cancelText: '取消',
    okType: 'danger',
    async onOk() {
      try {
        // 从当前URL中获取knowledge_id
        const currentPath = window.location.pathname
        const knowledgeId = currentPath.split('/documents/')[1]
        
        if (!knowledgeId) {
          message.error('未找到知识库ID')
          return
        }

        // 获取用户信息
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        if (!userInfo.userId || !userInfo.username) {
          message.error('未找到用户信息')
          return
        }

        // 调用删除接口，使用params传递参数
        const res = await http.delete(`/knowledge_api/${knowledgeId}/doc`, {
          params: {
            username: userInfo.username,
            user_id: userInfo.userId,
            document_id: record.key
          }
        })

        if (res.data.code === 200) {
          // 从文档列表中移除
          const index = documents.value.findIndex(doc => doc.key === record.key)
          if (index !== -1) {
            documents.value.splice(index, 1)
          }
          message.success('删除成功')
        } else {
          message.error(res.data.message || '删除失败')
        }
      } catch (error) {
        console.error('删除文档失败:', error)
        message.error(error.response?.data?.message || '删除失败')
      }
    }
  })
}

const handleBatchEmbed = () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请选择要嵌入的文档')
    return
  }
  
  Modal.confirm({
    title: '确认嵌入',
    content: `确定要对选中的 ${selectedRowKeys.value.length} 个文档进行嵌入吗？`,
    okText: '确认',
    cancelText: '取消',
    async onOk() {
      // TODO: 调用API进行批量嵌入
      const selectedDocs = documents.value.filter(doc => 
        selectedRowKeys.value.includes(doc.key)
      )
      selectedDocs.forEach(doc => {
        doc.embedStatus = EMBED_STATUS.PROCESSING
      })
      message.success('开始嵌入处理')
    }
  })
}

const handleBatchDelete = () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请选择要删除的文档')
    return
  }
  
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedRowKeys.value.length} 个文档吗？`,
    okText: '确认',
    cancelText: '取消',
    okType: 'danger',
    async onOk() {
      try {
        // 从当前URL中获取knowledge_id
        const currentPath = window.location.pathname
        const knowledgeId = currentPath.split('/documents/')[1]
        
        if (!knowledgeId) {
          message.error('未找到知识库ID')
          return
        }

        // 获取用户信息
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        if (!userInfo.userId || !userInfo.username) {
          message.error('未找到用户信息')
          return
        }

        // 调用批量删除接口，使用 body 传递参数
        const res = await http.delete(`/knowledge_api/${knowledgeId}/docs`, {
          data: {
            username: userInfo.username,
            user_id: userInfo.userId,
            document_ids: selectedRowKeys.value
          }
        })

        if (res.data.code === 200) {
          // 从文档列表中移除已删除的文档
          documents.value = documents.value.filter(doc => 
            !selectedRowKeys.value.includes(doc.key)
          )
          selectedRowKeys.value = []
          message.success('删除成功')
        } else {
          message.error(res.data.message || '删除失败')
        }
      } catch (error) {
        console.error('批量删除文档失败:', error)
        message.error(error.response?.data?.message || '删除失败')
      }
    }
  })
}

const fileInput = ref(null)

const handleAddFile = () => {
  fileInput.value?.click()
}

const handleFileChange = async (event) => {
  const files = event.target.files
  if (!files || files.length === 0) return

  try {
    // 显示上传中的提示
    const hide = message.loading('正在上传文件...', 0)
    
    // 从当前URL中获取knowledge_id
    const currentPath = window.location.pathname
    const knowledgeId = currentPath.split('/documents/')[1]
    
    if (!knowledgeId) {
      message.error('未找到知识库ID')
      return
    }

    // 获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.userId || !userInfo.username) {
      message.error('未找到用户信息')
      return
    }

    // 创建FormData对象
    const formData = new FormData()
    formData.append('username', userInfo.username)
    formData.append('user_id', userInfo.userId)

    // 上传每个文件
    for (const file of files) {
      formData.append('file', file)
      
      // 调用上传接口
      const res = await http.post(`/knowledge_api/${knowledgeId}/doc_upload`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })

      if (res.data.code === 200) {
        // 添加到文档列表
        documents.value.unshift({
          key: res.data.data.id, // 使用接口返回的id
          name: file.name,
          size: formatFileSize(file.size),
          chars: '0',
          updateTime: new Date().toLocaleString(),
          status: 'enabled',
          embedStatus: EMBED_STATUS.NOT_EMBEDDED
        })
      } else {
        message.error(`文件 ${file.name} 上传失败: ${res.data.message}`)
      }
    }
    
    hide()
    message.success(`成功上传 ${files.length} 个文件`)
    
    // 显示设置弹窗
    settingsModalVisible.value = true
  } catch (error) {
    message.error('文件上传失败')
    console.error('Upload error:', error)
  } finally {
    // 清空文件输入框
    event.target.value = ''
  }
}

// 添加文件大小格式化函数
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 修改分段分页配置
const segmentPagination = ref({
  current: 1,
  pageSize: 12,
  total: 0,
  showSizeChanger: true,
  pageSizeOptions: ['12', '24', '36'],
  showTotal: (total) => `共 ${total} 条`,
  onChange: (page) => {
    segmentPagination.value.current = page
    if (selectedDocument.value) {
      fetchSegments(selectedDocument.value.key)
    }
  },
  onShowSizeChange: (current, size) => {
    segmentPagination.value.pageSize = size
    segmentPagination.value.current = 1
    if (selectedDocument.value) {
      fetchSegments(selectedDocument.value.key)
    }
  }
})

// 修改获取分段数据的函数
const fetchSegments = async (documentId) => {
  try {
    // 从当前URL中获取knowledge_id
    const currentPath = window.location.pathname
    const knowledgeId = currentPath.split('/documents/')[1]
    
    if (!knowledgeId) {
      message.error('未找到知识库ID')
      return
    }

    // 获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.userId || !userInfo.username) {
      message.error('未找到用户信息')
      return
    }

    // 调用API获取分段数据
    const res = await http.get(`/knowledge_api/${knowledgeId}/segments`, {
      params: {
        user_id: userInfo.userId,
        username: userInfo.username,
        document_id: documentId,
        page: segmentPagination.value.current,
        limit: segmentPagination.value.pageSize
      }
    })

    if (res.data.code === 200) {
      // 更新分段列表
      sections.value = res.data.data.data.map((segment, index) => ({
        id: segment.id,
        index: (segmentPagination.value.current - 1) * segmentPagination.value.pageSize + index + 1,
        content: segment.content,
        chars: segment.word_count.toString(),
        tags: segment.keywords || [],
        enabled: segment.enabled // 添加enabled字段
      }))
      // 更新分页信息
      segmentPagination.value.total = res.data.data.total
    } else {
      message.error(res.data.message || '获取分段数据失败')
      sections.value = []
      segmentPagination.value.total = 0
    }
  } catch (error) {
    message.error('获取分段数据失败')
    sections.value = []
    segmentPagination.value.total = 0
  }
}

// 移除示例分段数据
const sections = ref([])

// 添加抽屉相关的响应式变量
const drawerVisible = ref(false)
const drawerTitle = ref('')
const sectionForm = ref({
  content: '',
  tags: []
})

// 添加标签相关的响应式变量
const tagInput = ref('')

// 添加标签相关的方法
const addTag = () => {
  if (tagInput.value && !sectionForm.value.tags.includes(tagInput.value)) {
    sectionForm.value.tags.push(tagInput.value)
    tagInput.value = ''
  }
}

const removeTag = (index) => {
  sectionForm.value.tags.splice(index, 1)
}

// 添加分段
const handleAddSection = () => {
  drawerTitle.value = '添加分段'
  sectionForm.value = {
    content: '',
    tags: []
  }
  drawerVisible.value = true
}

// 编辑分段
const handleEditSection = (section) => {
  drawerTitle.value = '编辑分段'
  sectionForm.value = {
    content: section.content,
    tags: [...section.tags]
  }
  drawerVisible.value = true
}

// 关闭抽屉
const handleDrawerClose = () => {
  drawerVisible.value = false
  sectionForm.value = {
    content: '',
    tags: []
  }
}

// 提交分段
const handleSectionSubmit = async () => {
  if (!sectionForm.value.content) {
    message.error('请输入分段内容')
    return
  }
  
  try {
    // 从当前URL中获取knowledge_id
    const currentPath = window.location.pathname
    const knowledgeId = currentPath.split('/documents/')[1]
    
    if (!knowledgeId) {
      message.error('未找到知识库ID')
      return
    }

    // 获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.userId || !userInfo.username) {
      message.error('未找到用户信息')
      return
    }

    // 准备请求参数
    const params = {
      username: userInfo.username,
      user_id: userInfo.userId,
      content: sectionForm.value.content,
      keywords: sectionForm.value.tags
    }

    let res
    if (drawerTitle.value === '编辑分段') {
      // 编辑分段
      const segmentId = sections.value.find(section => 
        section.content === sectionForm.value.content
      )?.id

      if (!segmentId) {
        message.error('未找到分段ID')
        return
      }

      res = await http.patch(
        `/knowledge_api/${knowledgeId}/documents/${selectedDocument.value.key}/segments/${segmentId}`,
        params
      )
    } else {
      // 添加分段
      res = await http.post(
        `/knowledge_api/${knowledgeId}/documents/${selectedDocument.value.key}/segments`,
        params
      )
    }

    if (res.data.code === 200) {
      message.success(drawerTitle.value === '编辑分段' ? '编辑成功' : '添加成功')
      // 刷新分段列表
      fetchSegments(selectedDocument.value.key)
      handleDrawerClose()
    } else {
      message.error(res.data.message || (drawerTitle.value === '编辑分段' ? '编辑失败' : '添加失败'))
    }
  } catch (error) {
    console.error(drawerTitle.value === '编辑分段' ? '编辑分段失败:' : '添加分段失败:', error)
    message.error(error.response?.data?.message || (drawerTitle.value === '编辑分段' ? '编辑失败' : '添加失败'))
  }
}

// 分段相关的响应式变量
const sectionSearchText = ref('')
const selectedSectionKeys = ref([])

// 分段搜索处理函数
const handleSectionSearch = (value) => {
  sectionSearchText.value = value
  // TODO: 实现分段搜索逻辑
}

// 批量删除分段
const handleBatchDeleteSections = async () => {
  if (selectedSectionKeys.value.length === 0) {
    message.warning('请选择要删除的分段')
    return
  }

  Modal.confirm({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedSectionKeys.value.length} 个分段吗？`,
    okText: '确认',
    cancelText: '取消',
    okType: 'danger',
    async onOk() {
      try {
        const currentPath = window.location.pathname
        const knowledgeId = currentPath.split('/documents/')[1]
        
        if (!knowledgeId) {
          message.error('未找到知识库ID')
          return
        }

        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        if (!userInfo.userId || !userInfo.username) {
          message.error('未找到用户信息')
          return
        }

        const res = await http.delete(`/knowledge_api/${knowledgeId}/segments`, {
          data: {
            username: userInfo.username,
            user_id: userInfo.userId,
            document_id: selectedDocument.value.key,
            segment_ids: selectedSectionKeys.value
          }
        })

        if (res.data.code === 200) {
          // 从分段列表中移除已删除的分段
          sections.value = sections.value.filter(section => 
            !selectedSectionKeys.value.includes(section.id)
          )
          selectedSectionKeys.value = []
          message.success('删除成功')
        } else {
          message.error(res.data.message || '删除失败')
        }
      } catch (error) {
        console.error('批量删除分段失败:', error)
        message.error(error.response?.data?.message || '删除失败')
      }
    }
  })
}

const handleSectionSelect = (sectionId) => {
  const index = selectedSectionKeys.value.indexOf(sectionId)
  if (index === -1) {
    selectedSectionKeys.value.push(sectionId)
  } else {
    selectedSectionKeys.value.splice(index, 1)
  }
}

const handleSectionCheckboxChange = (e, sectionId) => {
  if (e.target.checked) {
    if (!selectedSectionKeys.value.includes(sectionId)) {
      selectedSectionKeys.value.push(sectionId)
    }
  } else {
    const index = selectedSectionKeys.value.indexOf(sectionId)
    if (index !== -1) {
      selectedSectionKeys.value.splice(index, 1)
    }
  }
}

// 添加点击其他地方取消编辑的功能
const handleClickOutside = (event) => {
  if (editingDocument.value && !event.target.closest('.name-cell')) {
    handleEditCancel()
  }
}

// 添加获取文档列表的函数
const fetchDocuments = async () => {
  try {
    loading.value = true  // 显示加载动画
    
    // 从当前URL中获取uid
    const currentPath = window.location.pathname
    const uid = currentPath.split('/documents/')[1]
    
    if (!uid) {
      message.error('未找到知识库ID')
      return
    }

    // 获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.userId || !userInfo.username) {
      message.error('未找到用户信息')
      return
    }

    // 调用API获取文档列表
    const res = await http.get(`/knowledge_api/${uid}/doc`, {
      params: {
        user_id: userInfo.userId,
        username: userInfo.username
      }
    })

    if (res.data.code === 200) {
      // 更新文档列表
      documents.value = res.data.data.map(doc => ({
        key: doc.id,
        name: doc.name,
        size: `${doc.tokens}`,
        chars: doc.word_count.toString(),
        updateTime: new Date(doc.created_at * 1000).toLocaleString(),
        status: doc.enabled ? 'enabled' : 'disabled',
        embedStatus: doc.indexing_status === 'completed' ? 'completed' : 
                    doc.indexing_status === 'processing' ? 'processing' : 
                    doc.indexing_status === 'error' ? 'failed' : 'not_embedded'
      }))
    } else {
      message.error(res.data.message || '获取文档列表失败')
    }
  } catch (error) {
    message.error('获取文档列表失败')
  } finally {
    loading.value = false  // 隐藏加载动画
  }
}

// 设置相关
const settingsModalVisible = ref(false)
const settingsLoading = ref(false)
const settingsForm = ref({
  segmentIdentifier: '',
  maxSegmentLength: 500,
  segmentOverlap: 50,
  preprocessingRules: []
})

// 添加计算属性来处理segmentIdentifier的显示
const displaySegmentIdentifier = computed({
  get: () => {
    return settingsForm.value.segmentIdentifier.replace(/\n/g, '\\n')
  },
  set: (value) => {
    settingsForm.value.segmentIdentifier = value.replace(/\\n/g, '\n')
  }
})

// 添加获取处理规则的函数
const fetchProcessRules = async () => {
  try {
    // 从当前URL中获取knowledge_id
    const currentPath = window.location.pathname
    const knowledgeId = currentPath.split('/documents/')[1]
    
    if (!knowledgeId) {
      message.error('未找到知识库ID')
      return
    }

    // 获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.userId || !userInfo.username) {
      message.error('未找到用户信息')
      return
    }

    // 调用获取处理规则接口
    const res = await http.get(`/knowledge_api/${knowledgeId}/get_process_rule`, {
      params: {
        username: userInfo.username,
        user_id: userInfo.userId
      }
    })

    if (res.data.code === 200) {
      // 更新设置表单
      const { rules } = res.data.data
      const preprocessingRules = []
      
      // 处理预处理规则
      if (rules.pre_processing_rules) {
        rules.pre_processing_rules.forEach(rule => {
          if (rule.enabled) {
            preprocessingRules.push(rule.id)
          }
        })
      }

      settingsForm.value = {
        segmentIdentifier: rules.segmentation?.delimiter || '\n',
        maxSegmentLength: rules.segmentation?.max_tokens || 500,
        segmentOverlap: rules.segmentation?.chunk_overlap || 50,
        preprocessingRules
      }
    } else {
      console.error('获取处理规则失败:', error)
    }
  } catch (error) {
    console.error('获取处理规则失败:', error)
  }
}

const showSettingsModal = () => {
  settingsModalVisible.value = true
}

const handleSettingsSubmit = async () => {
  try {
    settingsLoading.value = true
    
    // 从当前URL中获取knowledge_id
    const currentPath = window.location.pathname
    const knowledgeId = currentPath.split('/documents/')[1]
    
    if (!knowledgeId) {
      message.error('未找到知识库ID')
      return
    }

    // 获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.userId || !userInfo.username) {
      message.error('未找到用户信息')
      return
    }

    // 获取所有上传的文件ID
    const fileIds = documents.value
      .filter(doc => doc.embedStatus === 'not_embedded')
      .map(doc => doc.key) // 直接使用key，因为key就是文件ID

    if (fileIds.length === 0) {
      message.warning('没有需要处理的文件')
      return
    }

    // 处理分段符
    let separator = settingsForm.value.segmentIdentifier
    if (separator === '\n' || separator === '\\n') {
      separator = '\n\n'
    }

    // 准备请求参数
    const params = {
      username: userInfo.username,
      user_id: userInfo.userId,
      file_ids: fileIds,
      remove_extra_spaces: settingsForm.value.preprocessingRules.includes('remove_extra_spaces'),
      remove_urls_emails: settingsForm.value.preprocessingRules.includes('remove_urls_emails'),
      separator: separator,
      max_tokens: settingsForm.value.maxSegmentLength,
      chunk_overlap: settingsForm.value.segmentOverlap
    }

    // 调用嵌入文本接口
    const res = await http.post(`/knowledge_api/${knowledgeId}/embed_text`, params)

    if (res.data.code === 200) {
      message.success('设置保存成功，开始处理文件')
      // 更新文件状态
      fileIds.forEach(fileId => {
        const doc = documents.value.find(d => d.key === fileId)
        if (doc) {
          doc.embedStatus = 'processing'
        }
      })
      settingsModalVisible.value = false
    } else {
      message.error(res.data.message || '保存设置失败')
    }
  } catch (error) {
    console.error('保存设置失败:', error)
    message.error(error.response?.data?.message || '保存设置失败')
  } finally {
    settingsLoading.value = false
  }
}

const handleSettingsCancel = () => {
  settingsModalVisible.value = false
}

// 添加轮询相关的变量
const pollingTimer = ref(null)

// 检查是否有文件正在处理
const hasProcessingFiles = computed(() => {
  return documents.value.some(doc => 
    doc.embedStatus === EMBED_STATUS.PROCESSING || 
    doc.embedStatus === EMBED_STATUS.QUEUED
  )
})

// 启动轮询
const startPolling = () => {
  if (!pollingTimer.value) {
    pollingTimer.value = setInterval(fetchDocuments, 3000)
  }
}

// 停止轮询
const stopPolling = () => {
  if (pollingTimer.value) {
    clearInterval(pollingTimer.value)
    pollingTimer.value = null
  }
}

// 监听文件状态变化
watch(hasProcessingFiles, (newValue) => {
  if (newValue) {
    startPolling()
  } else {
    stopPolling()
  }
}, { immediate: true })

// 批量启用分段
const handleBatchEnableSections = async () => {
  if (selectedSectionKeys.value.length === 0) {
    message.warning('请选择要启用的分段')
    return
  }

  try {
    const currentPath = window.location.pathname
    const knowledgeId = currentPath.split('/documents/')[1]
    
    if (!knowledgeId) {
      return
    }

    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.userId || !userInfo.username) {
      return
    }

    const res = await http.patch(`/knowledge_api/${knowledgeId}/enable_segments`, {
      username: userInfo.username,
      user_id: userInfo.userId,
      document_id: selectedDocument.value.key,
      segment_ids: selectedSectionKeys.value
    })

    if (res.data.code === 200) {
      // 更新分段状态
      sections.value.forEach(section => {
        if (selectedSectionKeys.value.includes(section.id)) {
          section.enabled = true
        }
      })
      message.success('启用成功')
    } else {
      message.error(res.data.message || '启用失败')
    }
  } catch (error) {
    console.error('批量启用分段失败:', error)
    message.error(error.response?.data?.message || '启用失败')
  }
}

// 批量禁用分段
const handleBatchDisableSections = async () => {
  if (selectedSectionKeys.value.length === 0) {
    message.warning('请选择要禁用的分段')
    return
  }

  try {
    const currentPath = window.location.pathname
    const knowledgeId = currentPath.split('/documents/')[1]
    
    if (!knowledgeId) {
      return
    }

    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.userId || !userInfo.username) {
      return
    }

    const res = await http.patch(`/knowledge_api/${knowledgeId}/disable_segments`, {
      username: userInfo.username,
      user_id: userInfo.userId,
      document_id: selectedDocument.value.key,
      segment_ids: selectedSectionKeys.value
    })

    if (res.data.code === 200) {
      // 更新分段状态
      sections.value.forEach(section => {
        if (selectedSectionKeys.value.includes(section.id)) {
          section.enabled = false
        }
      })
      message.success('禁用成功')
    } else {
      message.error(res.data.message || '禁用失败')
    }
  } catch (error) {
    console.error('批量禁用分段失败:', error)
    message.error(error.response?.data?.message || '禁用失败')
  }
}

// 添加召回历史相关的响应式变量
const recallHistory = ref([])
const recallHistoryPagination = ref({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  pageSizeOptions: ['20', '50', '100'],
  showTotal: (total) => `共 ${total} 条`,
  onChange: (page) => {
    recallHistoryPagination.value.current = page
    fetchRecallHistory()
  },
  onShowSizeChange: (current, size) => {
    recallHistoryPagination.value.pageSize = size
    recallHistoryPagination.value.current = 1
    fetchRecallHistory()
  }
})

// 添加获取召回历史的函数
const fetchRecallHistory = async () => {
  try {
    // 从当前URL中获取knowledge_id
    const currentPath = window.location.pathname
    const knowledgeId = currentPath.split('/documents/')[1]
    
    if (!knowledgeId) {
      return
    }

    // 获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.userId || !userInfo.username) {
      return
    }

    // 调用获取召回历史接口
    const res = await http.get(`/knowledge_api/${knowledgeId}/recall_test_history`, {
      params: {
        username: userInfo.username,
        user_id: userInfo.userId,
        page: recallHistoryPagination.value.current,
        limit: recallHistoryPagination.value.pageSize
      }
    })

    if (res.data.code === 200) {
      // 更新召回历史列表
      recallHistory.value = res.data.data.data.map(item => ({
        id: item.id,
        content: item.content,
        source: item.source,
        sourceAppId: item.source_app_id,
        createdByRole: item.created_by_role,
        createdBy: item.created_by,
        createdAt: new Date(item.created_at * 1000).toLocaleString()
      }))
      // 更新分页信息
      recallHistoryPagination.value.total = res.data.data.total
    } else {
      recallHistory.value = []
      recallHistoryPagination.value.total = 0
    }
  } catch (error) {
    console.error('获取召回历史失败:', error)
    recallHistory.value = []
    recallHistoryPagination.value.total = 0
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
  fetchDocuments()
  fetchProcessRules()
  fetchRecallHistory() // 添加获取召回历史的调用
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
  stopPolling() // 组件卸载时停止轮询
})
</script>

<style scoped>
.document-management {
  display: flex;
  margin-top: 0.5%;
  margin-left: 0.5%;
  margin-right: 0.5%;
  height: 95%;
}

.left-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  max-height: 81vh;
  min-height: 800px;
}

.left-content.collapsed {
  width: calc(50% - 8px);
  flex: none;
}

.green-separator {
  width: 0;
  height: 100%;
  max-height: 81vh;
  min-height: 800px;
  border-radius: 4px;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  flex-shrink: 0;
  visibility: hidden;
  opacity: 0;
}

.green-separator.visible {
  width: 8px;
  visibility: visible;
  opacity: 1;
}

.right-content {
  width: 0;
  height: 100%;
  max-height: 81vh;
  min-height: 800px;
  background: white;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  opacity: 0;
  transform: translateX(100%);
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  visibility: hidden;
  flex-shrink: 0;
}

.right-content.visible {
  width: 50%;
  opacity: 1;
  transform: translateX(0);
  visibility: visible;
}

.collapse-button-wrapper {
  position: absolute;
  left: calc(40% - 16px);
  top: 50%;
  transform: translateY(-50%);
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.collapse-btn-center {
  width: 32px;
  height: 32px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.collapse-btn-center:hover {
  background: #f5f5f5;
}

.arrow-collapsed {
  transform: rotate(180deg);
}

.search-container {
  height: 64px;
  margin-bottom: 0;
  padding: 16px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.detail-header {
  height: 64px;
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
}

.detail-header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}

.doc-title {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 16px;
  font-weight: 500;
}

.section-count {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
  font-weight: normal;
}

.detail-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.search-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.batch-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.name-cell {
  display: flex;
  align-items: center;
  overflow: hidden;
  width: 100%;
  gap: 8px;
}

.name-text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
  flex: 1;
}

.name-text:hover {
  color: #1890ff;
}

.embed-status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.document-list {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  border-radius: 8px;
  background: white;
  padding: 0;
  margin-bottom: 24px;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
}

:deep(.ant-table-wrapper) {
  flex: 1;
  border-radius: 8px;
  padding: 0 16px 16px;
  overflow: hidden;
  background: white;
}

:deep(.ant-table) {
  height: 100%;
  background: white;
}

:deep(.ant-table-tbody > tr > td) {
  padding: 12px 16px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

:deep(.ant-table-thead > tr > th) {
  background: white;
  border-bottom: 1px solid #f0f0f0;
  padding: 12px 16px;
  font-weight: 500;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: #fafafa;
}

:deep(.ant-table-pagination) {
  margin: 16px 16px 8px !important;
}

.collapse-btn {
  padding: 4px 8px;
  margin-right: 8px;
  border-radius: 4px;
}

.collapse-btn:hover {
  background: #f5f5f5;
}

.sections-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  overflow: hidden;
}

.sections-list {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  padding: 16px;
  overflow-y: auto;
  background: white;
}

.section-card {
  background: #f5f9ff;
  border-radius: 8px;
  border: 1px solid #e6f4ff;
  padding: 16px;
  display: flex;
  flex-direction: column;
  transition: all 0.3s;
  cursor: pointer;
  height: 180px;
}

.section-card.selected {
  background: #fff8f7;
  border-color: #ffa39e;
}

.section-card:hover {
  background: #eaf4ff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-index {
  font-weight: 500;
  color: #1890ff;
}

.char-count {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
}

.section-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.3s;
}

.section-card:hover .section-actions {
  opacity: 1;
}

.section-card.selected .section-actions {
  opacity: 1;
}

.section-checkbox {
  margin-right: 4px;
}

.section-content {
  flex: 1;
  font-size: 14px;
  line-height: 1.6;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 4;
  -webkit-box-orient: vertical;
  max-height: calc(180px - 80px); /* 减去头部和底部的高度 */
}

.section-footer {
  display: flex;
  align-items: center;
}

.section-tags {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #666;
  max-height: 20px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.ant-tag) {
  margin: 0;
  padding: 0 8px;
  height: 22px;
  line-height: 20px;
  font-size: 11px;
  border-radius: 3px;
}

:deep(.ant-tag.ant-tag-success) {
  color: #52c41a;
  background: #f6ffed;
  border-color: #b7eb8f;
}

:deep(.ant-tag.ant-tag-default) {
  color: rgba(0, 0, 0, 0.65);
  background: #f5f5f5;
  border-color: #d9d9d9;
}

:deep(.section-card .ant-tag) {
  background: #21252b;
  border-color: #4b5263;
  color: #e5c07b;
}

:deep(.section-card .ant-tag-close-icon) {
  color: #e5c07b;
  margin-left: 8px;
}

:deep(.section-card .ant-tag-close-icon:hover) {
  color: #f8c555;
}

:deep(.tags-list .ant-tag) {
  background: #fff7e6;
  border-color: #ffd591;
  color: #fa8c16;
  height: 24px;
  line-height: 22px;
  font-size: 12px;
  border-radius: 4px;
}

:deep(.tags-list .ant-tag-close-icon) {
  color: #fa8c16;
  margin-left: 8px;
}

:deep(.tags-list .ant-tag-close-icon:hover) {
  color: #ffa940;
}

.empty-sections {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: rgba(0, 0, 0, 0.45);
  font-size: 14px;
  background: white;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-left: auto;
}

.header-actions .ant-input-search {
  margin-right: 0;
}

:deep(.ant-checkbox-wrapper) {
  margin-right: 0;
}

:deep(.ant-checkbox) {
  margin-right: 0;
}

.tags-input-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  min-height: 32px;
}

.tag-input {
  width: 100%;
}

.markdown-editor {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
  line-height: 1.6;
  font-size: 14px;
}

:deep(.ant-drawer-body) {
  padding: 24px;
}

:deep(.ant-drawer-footer) {
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
}

.confirm-edit-btn {
  color: #52c41a;
  padding: 0 4px;
}

.confirm-edit-btn:hover {
  color: #73d13d;
}

.edit-actions {
  display: flex;
  gap: 4px;
  margin-left: 4px;
}

.cancel-edit-btn {
  color: #ff4d4f;
  padding: 0 4px;
}

.cancel-edit-btn:hover {
  color: #ff7875;
}

.segment-pagination {
  padding: 16px;
  display: flex;
  justify-content: flex-end;
  background: white;
  border-top: 1px solid #f0f0f0;
}

:deep(.ant-modal-body) {
  padding: 24px;
}

:deep(.ant-divider) {
  margin: 24px 0;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}

:deep(.ant-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 8px;
  background-color: #ff4d4f;
}

.status-dot.enabled {
  background-color: #52c41a;
}
</style> 